<template>
    <div class="login-container">
        <div class="content">
            <div class="close" @click="closeFun">
                <i class="el-icon-close"></i>
            </div>
            <!-- 登录form -->
            <el-form
                :model="loginInfo"
                ref="loginForm"
                :rules="rules"
                class="form"
                v-show="title === '用户登录'"
            >
                <p>{{ title }}</p>
                <el-form-item prop="name">
                    <el-input
                        type="text"
                        v-model="loginInfo.name"
                        class="input-box"
                        placeholder="请输入用户名"
                    >
                        <div slot="prefix" class="icon icon-user"></div>
                    </el-input>
                </el-form-item>
                <el-form-item prop="password">
                    <el-input
                        type="password"
                        v-model="loginInfo.password"
                        class="input-box"
                        placeholder="请输入密码"
                    >
                        <div slot="prefix" class="icon icon-pass"></div>
                    </el-input>
                </el-form-item>
                <el-form-item>
                    <button type="button" class="submit-btn" @click="userLogin">登录</button>
                    <button type="button" class="submit-btn" @click="changeForm('用户注册')">
                        注册
                    </button>
                </el-form-item>
            </el-form>
            <!-- 注册form -->
            <el-form
                :model="userInfo"
                ref="userForm"
                :rules="returnRules()"
                class="form"
                v-show="title === '用户注册'"
            >
                <p>{{ title }}</p>
                <el-form-item prop="name" :rules="returnRules().name">
                    <el-input
                        type="text"
                        v-model="userInfo.name"
                        class="input-box"
                        placeholder="请输入用户名"
                    >
                        <div slot="prefix" class="icon icon-user"></div>
                    </el-input>
                </el-form-item>
                <el-form-item prop="email" :rules="returnRules().email">
                    <el-input
                        type="text"
                        v-model="userInfo.email"
                        class="input-box"
                        placeholder="请输入邮箱"
                    >
                        <div slot="prefix" class="icon icon-pass"></div>
                    </el-input>
                </el-form-item>
                <el-form-item prop="telephone" :rules="returnRules().telephone">
                    <el-input
                        type="text"
                        v-model="userInfo.telephone"
                        class="input-box"
                        placeholder="请输入电话"
                    >
                        <div slot="prefix" class="icon icon-pass"></div>
                    </el-input>
                </el-form-item>
                <el-form-item prop="password" :rules="returnRules().password">
                    <el-input
                        type="password"
                        v-model="userInfo.password"
                        class="input-box"
                        placeholder="请输入密码"
                    >
                        <div slot="prefix" class="icon icon-pass"></div>
                    </el-input>
                </el-form-item>
                <el-form-item prop="checkPass" :rules="returnRules().checkPass">
                    <el-input
                        type="password"
                        v-model="userInfo.checkPass"
                        class="input-box"
                        placeholder="再次输入密码"
                    >
                        <div slot="prefix" class="icon icon-pass"></div>
                    </el-input>
                </el-form-item>
                <el-form-item prop="userIndustry" :rules="returnRules().userIndustry">
                    <el-select
                        v-model="userInfo.userIndustry"
                        placeholder="请选择用户行业"
                        class="input-box"
                    >
                        <el-option
                            v-for="item in userIndustrys"
                            :key="item.id"
                            :label="item.name"
                            :value="item.id"
                        ></el-option>
                        <div slot="prefix" class="icon icon-pass"></div>
                    </el-select>
                </el-form-item>
                <el-form-item prop="userType" :rules="returnRules().userType">
                    <el-select
                        v-model="userInfo.userType"
                        placeholder="请选择用户类型"
                        class="input-box"
                    >
                        <el-option
                            v-for="item in userTypes"
                            :key="item.id"
                            :label="item.name"
                            :value="item.id"
                        ></el-option>
                        <div slot="prefix" class="icon icon-pass"></div>
                    </el-select>
                </el-form-item>
                <!-- <el-checkbox v-model="checked">记住用户名和密码</el-checkbox> -->
                <el-form-item>
                    <button type="button" class="submit-btn" @click="changeForm('用户登录')">
                        返回登录
                    </button>
                    <button type="button" class="submit-btn" @click="userRegister('userForm')">
                        注册
                    </button>
                </el-form-item>
            </el-form>
        </div>
    </div>
</template>
<script>
import {
    login,
    register,
    checkName,
    checkEmail,
    getUserIndustry,
    getUserType,
} from '@/service/user';
import { setCookie } from 'U/utilCookie';
import dataCenterBus from 'U/dataCenterBus';
export default {
    name: 'login',
    data() {
        return {
            checkPass: '',
            title: '用户登录',
            checked: true,
            userInfo: {
                name: '',
                password: '',
                email: '',
                checkPass: '',
                telephone: '',
                userType: '',
                userIndustry: '',
            },
            loginInfo: {
                name: '',
                password: '',
            },
            rules: {
                name: [{ validator: this.validatelogName, trigger: 'blur' }],
                password: [{ required: true, message: '请输入密码', trigger: 'blur' }],
            },
            userTypes: [],
            userIndustrys: [],
        };
    },
    mounted() {
        // $(document).keyup(function (event) {
        //     if (event.keyCode === 13) {
        //         $('.submit').trigger('click');
        //     }
        // });
        getUserType().then(resData => {
            if (resData.status === 200) {
                this.userTypes = resData.data;
            }
        });
        getUserIndustry().then(resData => {
            if (resData.status === 200) {
                this.userIndustrys = resData.data;
            }
        });
    },
    methods: {
        closeFun() {
            this.$parent.loginShow = false;
        },
        // 校验方法
        returnRules() {
            let rules = {
                email: [{ validator: this.validateEmail, trigger: 'blur' }],
                telephone: [{ validator: this.validateTelPhone, trigger: 'blur' }],
                name: [{ validator: this.validateName, trigger: 'blur' }],
                password: [{ required: true, message: '请输入密码', trigger: 'blur' }],
                checkPass: [{ validator: this.validateCheckPass, trigger: 'blur' }],
                userType: [{ validator: this.validateUserType, trigger: 'blur' }],
                userIndustry: [{ validator: this.validateUserIndustry, trigger: 'blur' }],
            };
            return rules;
        },
        // 姓名是否已存在
        validateName(rule, value, callback) {
            if (value === '') {
                callback(new Error('请输入名称'));
            } else if (value.length < 3 || value.length > 18) {
                callback(new Error('长度在 3 到 18 个字符'));
            } else {
                checkName(value)
                    .then(resData => {
                        if (resData.data.code === '200') {
                            callback();
                        } else {
                            callback(new Error('该用户名已存在'));
                        }
                    })
                    .catch(error => {
                        callback(new Error('请检查网络'));
                    });
            }
        },
        // 姓名是否不存在
        validatelogName(rule, value, callback) {
            if (value === '') {
                callback(new Error('请输入名称'));
            } else if (value.length < 3 || value.length > 18) {
                callback(new Error('长度在 3 到 18 个字符'));
            } else {
                checkName(value)
                    .then(resData => {
                        if (resData.data.code === '200') {
                            callback(new Error('该用户名不存在'));
                        } else {
                            callback();
                        }
                    })
                    .catch(error => {
                        callback(new Error('请检查网络'));
                    });
            }
        },
        // 手机号校验
        validateTelPhone(rule, value, callback) {
            if (value === '') {
                callback(new Error('请输入手机号'));
            } else {
                if (/^1[3-9]\d{9}$/.test(value)) {
                    callback();
                } else {
                    callback(new Error('请输入正确手机号'));
                }
            }
        },
        // 邮箱校验
        validateEmail(rule, value, callback) {
            if (value === '') {
                callback(new Error('请输入邮箱'));
            } else {
                let checkEmailReg = /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
                if (checkEmailReg.test(value)) {
                    // 校验邮箱是否已存在
                    checkEmail(value)
                        .then(resData => {
                            if (resData.data.code === '200') {
                                callback();
                            } else {
                                callback(new Error('该邮箱已存在'));
                            }
                        })
                        .catch(error => {
                            callback(new Error('请检查网络'));
                        });
                } else {
                    callback(new Error('请输入正确邮箱'));
                }
            }
        },
        // 检查两次输入的密码是否一致
        validateCheckPass(rule, value, callback) {
            if (value === '') {
                callback(new Error('请再次输入密码'));
            } else {
                if (this.userInfo.password) {
                    if (value === this.userInfo.password) {
                        callback();
                    } else {
                        callback(new Error('两次输入密码不一致'));
                    }
                } else {
                    callback(new Error('请输入密码'));
                }
            }
        },
        validateUserType(rule, value, callback) {
            if (value === '') {
                callback(new Error('请选择用户类型'));
            } else {
                callback();
            }
        },
        validateUserIndustry(rule, value, callback) {
            if (value === '') {
                callback(new Error('请选择用户行业'));
            } else {
                callback();
            }
        },
        // 切换登录注册表单时清空验证及数据
        changeForm(name) {
            this.$refs.loginForm.resetFields();
            this.title = name;
            this.$refs.userForm.resetFields();
        },
        async userLogin() {
            let that = this;
            this.$refs['loginForm'].validate(async valid => {
                if (valid) {
                    const resData = await login(that.loginInfo);
                    if (resData.status === 200) {
                        if (resData.data.status === '104') {
                            this.$message({
                                message: '密码错误，请重新输入！',
                                type: 'warning',
                                offset: 200,
                            });
                            return false;
                        }
                        // if (that.checked) {
                        //     that.savePassword();
                        // }
                        localStorage.setItem('userAuthorization', resData.data.user.token);
                        localStorage.setItem(
                            'userInf',
                            JSON.stringify({ name: resData.data.user.name })
                        );
                        that.$emit('changeName', resData.data.user.name);
                        that.$message.success('登录成功！');
                        dataCenterBus.$emit('isLogin', false);
                        that.$parent.loginShow = false;
                    } else {
                        this.$message({
                            message: '登录失败，请联系管理员！',
                            type: 'warning',
                            offset: 200,
                        });
                    }
                } else {
                    this.$message({
                        message: '请检查填写是否合格！',
                        type: 'warning',
                        offset: 200,
                    });
                    return false;
                }
            });
        },
        savePassword() {
            setCookie(this.userInfo.name, this.userInfo.password);
        },
        async userRegister(formName) {
            let that = this;
            this.$refs[formName].validate(valid => {
                if (valid) {
                    let param = {
                        email: that.userInfo.email,
                        name: that.userInfo.name,
                        password: that.userInfo.password,
                        siteId: that.userInfo.siteId,
                        telephone: that.userInfo.telephone,
                        userType: that.userInfo.userType,
                        userIndustry: that.userInfo.userIndustry,
                    };
                    that.registerHandle(param);
                } else {
                    return false;
                }
            });
        },
        // 注册先经过邮箱激活
        async registerHandle(param) {
            let resData = await register(param);
            if (resData.status === 200) {
                if (resData.data.code !== '200') {
                    this.$message({
                        message: resData.data.message,
                        type: 'warning',
                        offset: 200,
                    });
                    return false;
                }
                // 勾选保存用户名密码
                if (this.checked) {
                    this.savePassword();
                }
                this.$alert('<span>已向您的邮箱发送验证信息，请查看</span>', '成功', {
                    dangerouslyUseHTMLString: true,
                    customClass: 'messageBoxClass',
                    confirmButtonClass: 'messageBoxSureBtn',
                    callback: (action, instance) => {
                        if (action === 'confirm') {
                            this.title = '用户登录';
                            this.$refs['userForm'].resetFields();
                        }
                    },
                });
            } else {
                this.$message({
                    message: '请检查填写是否合格！',
                    type: 'warning',
                    offset: 200,
                });
            }
        },
    },
};
</script>
<style lang="scss">
.login-container {
    position: absolute;
    top: 0px;
    left: 0px;
    width: 100%;
    height: 100%;
    background: rgba(0, 0, 0, 0.6);
    z-index: 1000;
    font-size: 62.5%;
    .content {
        position: absolute;
        top: 50%;
        left: 50%;
        width: 575px;
        max-height: 700px;
        transform: translate(-50%, -50%);
        border: 3px solid rgb(39, 173, 249);
        border-radius: 7px;
        .close {
            float: right;
            color: #fff;
            font-size: 25px;
            margin-right: 10px;
            margin-top: 10px;
        }
    }
    .content .form {
        color: white;
        width: 100%;
        height: 100%;
    }
    .content .form p {
        font-size: 28px;
        color: #00e1eb;
        margin-bottom: 45px;
    }
    .input-item {
        display: flex;
        margin-bottom: 20px;
        background-color: rgba(23, 78, 109, 0.4);
        width: 440px;
        margin: auto;
        margin-bottom: 30px;
        padding: 0 10px;
        border: 1px solid #0687cd;
    }
    .icon {
        width: 30px;
        height: 30px;
        display: flex;
        margin-top: 5px;
    }
    .content {
        .form {
            .el-form-item__content {
                width: 420px;
                margin: auto;
                .input-box {
                    width: 100%;
                    font-size: 20px;
                    border-radius: 2px;
                    outline: 0;
                    color: #fff;
                    position: relative;
                    border: none;
                    .icon {
                        position: absolute;
                        left: 5px;
                        top: 0;
                    }
                    .el-input {
                        font-size: inherit;
                    }
                    .icon-user {
                        background-image: url(./theme/img/user.png);
                        background-repeat: no-repeat;
                        background-size: cover;
                    }
                    .icon-pass {
                        background-image: url(./theme/img/password.png);
                        background-repeat: no-repeat;
                        background-size: cover;
                    }
                    .el-input__inner {
                        color: #fff;
                        background-color: rgba(23, 78, 109, 0.4);
                        padding-left: 45px;
                    }
                }
            }
        }
    }
    .input-box::-webkit-input-placeholder {
        color: #fff;
    }
    .content .form .submit-btn {
        width: 160px;
        height: 36px;
        overflow: hidden;
        display: inline-block;
        line-height: 5px;
        background-color: #133a3b;
        color: #fff;
        font-size: 20px;
        border: 1px solid #19f4fc;
        text-align: center;
        cursor: pointer;
        border-radius: 2px;
        //margin: auto;
        margin: 0px 20px;
        margin-bottom: 30px;
    }
}
</style>
